package com.kaaction.common.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.Map;

import com.google.gson.Gson;

public class WechatUtils {

	public static String APP_ID = "wx079bba8222507669";
	
	public static String APP_SECRET = "fa10d617075d0a950bec57977d3117ce";
	
	private final static String TICKET_TOKEN = "ticket_access_token";
	private final static String GET_TICKET_TOKEN_TIME = "get_tcket_token_time";
	
	private final static String TICKET_VALUE = "ticket_value";
	private final static String GET_TICKET_VALUE_TIME = "get_ticket_value_time";
	
	/**
	 * 判断缓存中的access token是否有效。
	 * @return
	 */
	private static boolean checkCacheToken() {
		Date now = new Date();
		Object tokenObj = CacheUtils.get(TICKET_TOKEN);
		if(tokenObj != null){
			Object getTokenTimeObj = CacheUtils.get(GET_TICKET_TOKEN_TIME);
			if(getTokenTimeObj != null){
				Date getTokenTime = (Date)getTokenTimeObj;
				long timeInterval = DateUtils.getSecondsDistanceOfTwoDate(getTokenTime, now);
				if(timeInterval > 0 && timeInterval < 7000){//改成7000秒，预留3分钟
					//缓存中两个值都存在，
					//2.GET_TICKET_TOKEN_TIME 可以转换为日期类型
					//3.当前日期和GET_TICKET_TOKEN_TIME日期差小于7200秒
					return true;
				}
			}
		}
		return false;
	}
	
	/**
	 * 判断缓存中的ticket是否有效。
	 * @return
	 */
	private static boolean checkTicket() {
		Date now = new Date();
		Object ticketObj = CacheUtils.get(TICKET_VALUE);
		if(ticketObj != null){
			Object getTicketValueObj = CacheUtils.get(GET_TICKET_VALUE_TIME);
			if(getTicketValueObj != null){
				Date getTicketValueTime = (Date)getTicketValueObj;
				long timeInterval = DateUtils.getSecondsDistanceOfTwoDate(getTicketValueTime, now);
				if(timeInterval > 0 && timeInterval < 7000){//改成7000秒，预留3分钟
					//缓存中两个值都存在，
					//2.GET_TICKET_TOKEN_TIME 可以转换为日期类型
					//3.当前日期和GET_TICKET_TOKEN_TIME日期差小于7200秒
					return true;
				}
			}
		}
		return false;
	}
	
	/**
	 * 获得ticket的token
	 * @return
	 */
	private static String getTicketToken() {
		if(checkCacheToken()){
			return (String)CacheUtils.get(TICKET_TOKEN);
		} else {
			String accessUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
					+ WechatUtils.APP_ID + "&secret=" + WechatUtils.APP_SECRET;
			String jsonx = loadJson(accessUrl);
			Gson gsx = new Gson();

			Map<String, String> mapx = gsx.fromJson(jsonx, Map.class);
			String accessToken = mapx.get("access_token");
			CacheUtils.put(TICKET_TOKEN, accessToken);
			CacheUtils.put(GET_TICKET_TOKEN_TIME, new Date());
			return accessToken;
		}
	}
	
	private static String getTicketByToken(String token) {
		String result = "";
		Gson gs = new Gson();
		String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + token
				+ "&type=jsapi";
		String json = loadJson(ticketUrl);
		Map<String, String> map = gs.fromJson(json, Map.class);
		if(map != null) {
			result = map.get("ticket");
			if(!StringUtils.isBlank(result)) {
				CacheUtils.put(TICKET_VALUE, result);
				CacheUtils.put(GET_TICKET_VALUE_TIME, new Date());
			}
		}
		return result;
	}
	
	public static String getTicket(){
		if(checkTicket()){
			return (String)CacheUtils.get(TICKET_VALUE);
		} else {
			String token = getTicketToken();
			return getTicketByToken(token);
		}
	}
	
	
	private static String loadJson(String url) {
		StringBuilder json = new StringBuilder();
		try {
			URL urlObject = new URL(url);
			URLConnection uc = urlObject.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
			String inputLine = null;
			while ((inputLine = in.readLine()) != null) {
				json.append(inputLine);
			}
			in.close();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return json.toString();
	}
}
